import axios, {
  AxiosInstance,
  AxiosError,
  AxiosRequestConfig,
  InternalAxiosRequestConfig,
  AxiosResponse,
} from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { LoginStore } from '@/store/login'

// 数据返回的接口
// 定义请求响应参数，不含data
interface Result {
  code: number
  message: string
}

// 请求响应参数，包含data
interface ResultData<T = any> extends Result {
  data?: T
}

const loginStore = LoginStore()
const URL: string = import.meta.env.VITE_GLOB_API_HOST as string
enum requestEnum {
  TIMEOUT = 20000,
  OVERDUE = 600, // 登录失败
  FAIL = 501, //请求失败
  SUCCESS = 200, //请求成功
  UNAUTHENTICATED = 401, //请登录
  INVALIDTOKEN = 406, //无效的Token或者登录过期,请重新登录
}

const config = {
  //默认地址
  baseURL: URL as string,
  //请求超时时间
  timeout: requestEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true,
}

class RequestHttp {
  // 定义成员变量并指定类型
  service: AxiosInstance
  public constructor(config: AxiosRequestConfig) {
    // 实例化axios
    this.service = axios.create({ ...config })

    /**
     *  请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (request: InternalAxiosRequestConfig) => {
        const token = loginStore.token || ''
        request.headers.Authorization = token
        return request
      },
      (err: AxiosError) => {
        // 请求报错
        Promise.reject(err)
      }
    )

    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        // 解构
        const { data } = response
        if (
          data.code === requestEnum.UNAUTHENTICATED ||
          data.code === requestEnum.INVALIDTOKEN
        ) {
          // 无效的Token或者登录过期,请重新登录
          loginStore.cleanLoginInfo()
          router.replace({ path: '/login' })
          return Promise.reject(data)
        }
        if (data.code === requestEnum.OVERDUE) {
          // 登录信息失效，应跳转到登录页面，并清空本地的token
          loginStore.cleanLoginInfo()
          router.replace({ path: '/login' })
          return Promise.reject(data)
        }
        // 全局错误信息拦截（防止下载文件得时候返回数据流，没有code，直接报错）
        if (data.code && data.code !== requestEnum.SUCCESS) {
          ElMessage.error(data.message)
          return Promise.reject(data)
        }
        return data
      },
      (error: AxiosError) => {
        const { response } = error

        if (response) {
          this.handleCode(response?.status)
        }
        if (!window.navigator.onLine) {
          ElMessage.error('网络连接失败')
        }
      }
    )
  }

  handleCode(code: number): void {
    switch (code) {
      case 401:
        ElMessage.error('登录失败，请重新登录')
        break
      default:
        ElMessage.error('请求失败')
        break
    }
  }

  // 常用方法封装
  get<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.get(url, { params })
  }

  post<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.post(url, params)
  }
  put<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.put(url, params)
  }

  delete<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.delete(url, { data: params })
  }
}

// 导出一个实例对象
export default new RequestHttp(config)
